package com.liuyi.netty.im.lychat.modular.controller;


import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.liuyi.netty.im.commons.codes.data.event.message.playload.PlayloadText;
import com.liuyi.netty.im.lychat.LychatConst;
import com.liuyi.netty.im.lychat.config.AsyncExecute;
import com.liuyi.netty.im.lychat.config.SaTokenConfig;
import com.liuyi.netty.im.lychat.config.base.BaseQueryController;
import com.liuyi.netty.im.lychat.modular.controller.model.UserModel;
import com.liuyi.netty.im.lychat.modular.controller.model.UserModel.Login;
import com.liuyi.netty.im.lychat.modular.entity.User;
import com.liuyi.netty.im.lychat.modular.enums.MessageType;
import com.liuyi.netty.im.lychat.modular.enums.SessionType;
import com.liuyi.netty.im.lychat.modular.service.IGroupService;
import com.liuyi.netty.im.lychat.modular.service.IMessageUserRecordsService;
import com.liuyi.netty.im.lychat.modular.service.IUserFriendService;
import com.liuyi.netty.im.lychat.modular.service.IUserService;
import com.liuyi.rapid.develop.tool.resp.RespCall;
import com.liuyi.rapid.develop.tool.resp.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Collections;

import static com.liuyi.rapid.develop.tool.resp.ResponseCall.success;
import static com.liuyi.rapid.develop.tool.resp.ResponseCall.successMsg;
import static org.springframework.http.ResponseEntity.ok;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author mybatis-plus
 * @since 2021-12-29
 */
@Api(value = "", tags = {"用户表"})
@RestController
@RequestMapping("/modular/user")
@Validated
public class UserController implements BaseQueryController<User, IUserService> {

    @Resource
    private IUserService userService;
    @Resource
    private IUserFriendService userFriendService;
    @Resource
    private IGroupService groupService;
    @Resource
    private IMessageUserRecordsService messageUserRecordsService;

    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", dataType = "string", name = "userId", value = "用户id")
    })
    @ApiOperation(value = "验证ID", notes = "true 说明存在，不可使用,false说明可以使用", httpMethod = "POST")
    @PostMapping(SaTokenConfig.ALL_PATH +"/checkUserId/{userId}")
    public ResponseEntity<Response<Boolean>> checkUserId(@PathVariable String userId) {
        return ok(success(server().count(User.USER_ID, userId) > 0));
    }

    @ApiOperation(value = "用户信息获取", notes = "", httpMethod = "GET")
    @GetMapping("/userInfo")
    public ResponseEntity<Response<User>> userInfo() {
        String userId = StpUtil.getLoginIdAsString();
        User user = server().cache().getById(userId);
        wrapper(user);
        return ok(success(user));
    }

    @ApiOperation(value = "注册", notes = "", httpMethod = "POST")
    @PostMapping("/registered")
    public ResponseEntity<Response<Void>> registered(@Valid @RequestBody UserModel.Registered p) {
        server().createUser(p.getUsername(), p.getPassword());
        AsyncExecute.me().async(() -> {
            userFriendService.createFriend(p.getUsername(), LychatConst.SYS_USER_ID, false);
            messageUserRecordsService.createSendMessage(LychatConst.SYS_USER_ID, p.getUsername(), SessionType.C2C, MessageType.TEXT,
                    PlayloadText.PlayloadTextBuilder.aPlayloadText().text("欢迎来到Lychat，祝您体验愉快").build());
        });
        AsyncExecute.me().async(() -> {
            String groupNo = groupService.createGroup("体验群", LychatConst.SYS_USER_ID, Collections.singletonList(p.getUsername()));
            messageUserRecordsService.createSendMessage(LychatConst.SYS_USER_ID, groupNo, SessionType.GROUP, MessageType.TEXT,
                    PlayloadText.PlayloadTextBuilder.aPlayloadText().text("欢迎来到Lychat，这里是体验群，祝您体验愉快").build());
        });
        return ok(successMsg("注册成功，请妥善保管您的账号"));
    }

    @ApiOperation(value = "登录", notes = "", httpMethod = "POST")
    @PostMapping("/login")
    public ResponseEntity<Response<SaTokenInfo>> login(@Valid @RequestBody Login p) {
        User user = server().getById(p.getUsername());
        if (user == null) {
            return RespCall.error("账号不存在");
        }
        if (!LychatConst.checkUserPassword(p.getPassword(), user.getPassword(), user.getSalt())) {
            return RespCall.error("密码错误");
        }
        StpUtil.login(user.getUserId());
        return ok(success(StpUtil.getTokenInfo()));
    }

    @Override
    public IUserService server() {
        return userService;
    }

    @Override
    public void wrapper(User data) {
        data.setPassword(null).setSalt(null);
    }
}

